package com.winning.bi.jms;

import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Queue;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.ActiveMQPrefetchPolicy;
import org.apache.activemq.RedeliveryPolicy;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;

/**
 * 
 * @author 张大川
 *
 */
public class ReceiveMessageUtils {
	public static String username;
	public static String password;
	public static String url;

	static

	{

		try {
			Configuration configuration = new PropertiesConfiguration("config/jms.properties");
			password = configuration.getString("password");
			username = configuration.getString("username");
			url = configuration.getString("url");
		} catch (ConfigurationException e) {

			e.printStackTrace();
		}

	}

	private static final class FactoryInstance {
		public static Connection con;
		static {
			try {
				ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(
						SendMessageUtils.username, SendMessageUtils.password, SendMessageUtils.url);

				ActiveMQPrefetchPolicy activeMQPrefetchPolicy = new ActiveMQPrefetchPolicy();
				activeMQPrefetchPolicy.setQueuePrefetch(1);
				activeMQConnectionFactory.setTrustAllPackages(true);
				activeMQConnectionFactory.setPrefetchPolicy(activeMQPrefetchPolicy);
				RedeliveryPolicy p1 = new RedeliveryPolicy();
				p1.setMaximumRedeliveries(3);

				activeMQConnectionFactory.setRedeliveryPolicy(p1);
				activeMQConnectionFactory.setOptimizeAcknowledge(false);
				con = activeMQConnectionFactory.createConnection();
			} catch (JMSException e) {

				e.printStackTrace();
			}
		}

	}

	public static final void close() throws JMSException {
		FactoryInstance.con.close();
	}

	/**
	 * 
	 * 接收消息并处理
	 * 
	 * @param queueName
	 * @param listener
	 * @throws JMSException
	 */
	public static void receiveMessage(String queueName, MessageListener listener) throws JMSException {
		Connection connection = ReceiveMessageUtils.FactoryInstance.con;
		connection.start();
		// 创建session
		Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

		Queue destination = session.createQueue(queueName);
		MessageConsumer messageConsumer = session.createConsumer(destination);

		messageConsumer.setMessageListener(listener);
		while (true) {

		}
	}
}
